import React, { ChangeEvent, useEffect, useRef, useState } from "react";
import MdEditor from "md-editor-rt";
import { Tooltip, Select, message } from "antd";
import { Writewrap } from "./styled";
import { uploadavatar } from "@/apis/user";
import { useNavigate } from "react-router-dom";
import { getalllabel } from "@/apis/label";
import { shallowEqual, useDispatch, useSelector } from "react-redux";
import { rootState } from "@/store";
import { publishapi } from "@/apis/essay";
import { usertype } from "@/store/reducers/home";
import { loginpatch } from "@/store/action/home";

const { Option } = Select;
export default function Write() {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [text, setText] = useState<string>("hello md-editor-rt！");
  const [title, setTile] = useState<string>(""); //标题
  const [cover, setCover] = useState<string>(""); //封面
  const [clabel, setClabel] = useState<number>(); //标签
  const [covervis, setCovervis] = useState<boolean>(false); //上传的封面是否显示
  const [label, setLabel] = useState<{ id: number; content: string }[]>([]);
  const coverref = useRef<HTMLInputElement>(null);
  const { user } = useSelector(
    (store: rootState) => ({
      user: store.home.user as usertype,
    }),
    shallowEqual
  );

  //获取所有标签
  useEffect(() => {
    getalllabel().then((res: any) => {
      setLabel(res.result);
    });
  }, []);

  //选择标签改变
  const handleChange = (labelid: number) => {
    setClabel(labelid);
  };
  //文章内容上传图片
  const onUploadImg = async (
    files: Array<File>,
    callback: (urls: string[]) => void
  ) => {
    const res = await Promise.all(
      files.map((file: File) => {
        return new Promise((rev, rej) => {
          const form = new FormData();
          form.set("picture", file);
          uploadavatar(form)
            .then((res: any) => {
              // console.log(res);
              return rev(res);
            })
            .catch((error) => rej(error));
        });
      })
    );

    callback(
      res.map((item: any) => {
        return item.result;
      })
    );
  };
  //封面上传
  const uploadcover = async (e: ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files) return;
    const formdata = new FormData();
    formdata.set("picture", e.target.files[0]);
    const re: any = await uploadavatar(formdata);
    setCover(re.result);
  };
  //发表文章
  const publish = async () => {
    if (!(text && clabel && cover && title)) return message.error("请填写完整");
    try {
      await publishapi(title, text, clabel, user.id, cover);
      message.success("发表文章成功");
      setTile("");
      setText("");
      setClabel(label[0].id);
      setCover("");
    } catch (e) {
      dispatch(loginpatch({}));
      navigate("/");
      message.error("身份失效");
    }
  };
  return (
    <Writewrap>
      <div className="top">
        <input
          type="text"
          value={title}
          onChange={(e) => setTile(e.target.value)}
          placeholder="请输入标题..."
        />
        <div className="right">
          {label.length > 0 && (
            <Select style={{ width: 120 }} onChange={handleChange}>
              {label.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.content}
                </Option>
              ))}
            </Select>
          )}
          <Tooltip placement="topLeft" title="上传封面">
            <span
              className="iconfont icon-shengchanfengmian"
              onClick={(e) => setCovervis(!covervis)}
            ></span>
          </Tooltip>
          {covervis && (
            <div className="cover">
              {cover !== "" ? (
                <div className="img">
                  <img src={cover} alt=""></img>
                  <span
                    className="iconfont icon-shanchu"
                    onClick={(e) => setCover("")}
                  ></span>
                </div>
              ) : (
                <span
                  className="iconfont icon-yunshangchuan"
                  onClick={(e) => coverref.current?.click()}
                >
                  <input
                    type="file"
                    onChange={uploadcover}
                    ref={coverref}
                    hidden
                  />
                </span>
              )}
            </div>
          )}
          <span className="public" onClick={publish}>
            发布
          </span>
          <span className="back" onClick={(e) => navigate(-1)}>
            返回
          </span>
        </div>
      </div>
      <MdEditor
        modelValue={text}
        onChange={setText}
        onUploadImg={onUploadImg}
        style={{ width: "100%", height: "800px" }}
      />
    </Writewrap>
  );
}
